package cn.iocoder.yudao.module.study.message.factory;

import cn.iocoder.yudao.module.study.message.handle.ISendMsgService;
import cn.iocoder.yudao.module.study.message.handle.enums.SendMsgTypeEnum;

import java.util.HashMap;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.study.enums.ErrorCodeConstants.*;
/**
 * @Author cjc
 * @Date 2024/3/19 16:15
 * @Description: 消息工厂类
 * @Version 1.0
 */
public class MessageHandleFactory {

    private static final Map<String, ISendMsgService> MAP_MSG_HANDLER = new HashMap<>(8);
    public static ISendMsgService getMsgHandle(String templateType) {
        ISendMsgService sendMsgHandle = MAP_MSG_HANDLER.get(templateType);
        if (sendMsgHandle == null) {
            synchronized (MessageHandleFactory.class) {
                sendMsgHandle = MAP_MSG_HANDLER.get(templateType);
                if (sendMsgHandle == null) {
                    SendMsgTypeEnum msgTypeEnum = SendMsgTypeEnum.getByType(templateType);
                    if (msgTypeEnum != null) {
                        try {
                            sendMsgHandle = (ISendMsgService)Class.forName(msgTypeEnum.getImplClass()).newInstance();
                        } catch (Exception e) {
                            //无法实例化消息服务类
                            throw exception(MSG_UNABLE_INSTANCE_IMPL);
                        }
                        MAP_MSG_HANDLER.put(templateType, sendMsgHandle);
                    }
                }
            }
        }
        if (sendMsgHandle == null) {
            //没有配置消息的服务类
            throw exception(MSG_INSTANCE_IMPL_IS_NOT_CONFIG);
        }
        return sendMsgHandle;
    }
}
